package com.example.first.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * @Author LSQ
 * @Description TODO Callable是带返回值的，现在模拟批处理的情况
 * @date 2021/8/7 22:55
 * @Version 1.0
 */


/**
 * 1、下面代码模拟提交了14个任务
 * 2、运行时会开启4个线程，其中3个是核心线程，1个是非核心线程
 */
public class LearnFuture6 {


    public static void main(String[] args) {
        ArrayBlockingQueue<Runnable> myWorkQueue = new ArrayBlockingQueue(10);
        List<String> myList = new ArrayList();
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("E");
        myList.add("F");
        myList.add("G");
        myList.add("H");
        myList.add("I");
        myList.add("J");
        myList.add("K");
        myList.add("L");
        myList.add("M");
        myList.add("N");
        myList.add("O");

        ExecutorService executorService = new ThreadPoolExecutor(3, 5, 60, TimeUnit.SECONDS, myWorkQueue);
        ArrayList<Future> futureArrayList = new ArrayList<>();
        for (String dealTaskStr : myList
        ) {
            Callable<String> callable = () -> {
                int sleepTime = new Random().nextInt(10) + 1;
                System.out.println(Thread.currentThread().getName() + " will cost: " + sleepTime + " seconds!");
                Thread.sleep(sleepTime * 1000);
                String result = "########################### " + Thread.currentThread().getName() + " is deal: " + dealTaskStr;
                return result;
            };

            Future<String> future = executorService.submit(callable);
            futureArrayList.add(future);

        }


        for (Future myFuture : futureArrayList
        ) {
            try {
                // get会阻塞，要等任务执行完成才返回！
                System.out.println(myFuture.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        executorService.shutdown();

    }
}


